<!--
 * @Author: 常安民 changanmin1@crdigital.com.cn
 * @Date: 2024-07-26 18:10:50
 * @LastEditors: 常安民 changanmin1@crdigital.com.cn
 * @LastEditTime: 2024-08-05 16:16:10
 * @FilePath: /console-web/src/views/trip/manager/standard/standard.vue
 * @Description: 差标管理
 * @email:anmin@foxmail.com
 * Copyright (c) 2024 by 华润数科控股有限公司/常安民, All Rights Reserved. 
-->
<template>
  <!-- 页面-角色管理 -->
  <div class="innerPageTable-out-flex">
    <!-- 搜索区域 -->
    <SelfAdaption>
      <Form
        :model="searchForm"
        ref="searchForm"
        slot="adaption-bar"
        label-position="top"
        class="ivu-form-no-margin-bottom"
        inline
      >
        <template>
          <FormItem prop="businessUnit" label="BU编码">
            <Input
              type="text"
              :maxlength="30"
              v-model.trim="searchForm['businessUnit']"
              placeholder="请输入BU编码"
              clearable
              @on-enter="search"
            ></Input>
          </FormItem>

          <FormItem prop="company" label="公司编码">
            <Input
              type="text"
              v-model.trim="searchForm['company']"
              placeholder="请输入公司编号"
              clearable
              @on-enter="search"
            ></Input>
          </FormItem>

          <FormItem prop="companyDescr" label="公司名称">
            <Input
              type="text"
              v-model.trim="searchForm['companyDescr']"
              placeholder="请输入公司名称"
              clearable
              @on-enter="search"
            ></Input>
          </FormItem>

          <FormItem prop="tenantCode" label="所属租户" v-if="isPlatformAdmin">
            <Select
              label-in-value
              filterable
              v-model="searchForm.tenantCode"
              style="width: 100%" 
              clearable
            >
              <Option v-for="tenant in tenantList" :value="tenant.tenantCode" :key="tenant.id">
                {{ tenant.tenantName }}  -  {{ tenant.tenantCode }}
              </Option>
            </Select>
          </FormItem> 

          <FormItem prop="standard" label="差旅编码">
            <Input
              type="text"
              v-model.trim="searchForm['standard']"
              placeholder="请输入差旅编码"
              clearable
              @on-enter="search"
            ></Input>
          </FormItem>

          <FormItem prop="supvLvlId" label="职级编号">
            <Input
              type="text"
              v-model.trim="searchForm['supvLvlId']"
              placeholder="请输入职级编号"
              clearable
              @on-enter="search"
            ></Input>
          </FormItem>

          <FormItem prop="crcSupvLvlDesc" label="职级名称">
            <Input
              type="text"
              v-model.trim="searchForm['crcSupvLvlDesc']"
              placeholder="请输入职级名称"
              clearable
              @on-enter="search"
            ></Input>
          </FormItem>
          <!-- 查询\重置按钮 -->
          <FormItem prop="button" class="search-solt-btn">
            <RPButton optType="search" @click="search" />
            <RPButton optType="reset" @click="reset" />
          </FormItem>
        </template>
      </Form>
    </SelfAdaption>

    <InnerPageTable ref="searchTable" :config="tableConfig">
      <!-- table bar 添加-->
      <div slot="table-bar">
        <RPButton optType="create" @click="onOpenAddPage" /> 
      </div>
    </InnerPageTable>
  </div>
</template>

<script>
import { queryTSJLM,  deleteTSJLM } from '@api/trip/standard/standardRank.js';
import debounce from "lodash/debounce";

import tenantAPI from "@/api/tenantApi.js";

import { searchAppListByTenantCode } from '@/api/applicationApi.js';

import valueSetAPI from '@/api/valueSetAPI.js';
import { CoreModuleName } from '@/const.js';
import { mapGetters } from 'vuex';
export default {
  name: 'trip-manager-standard-rank',
  mixins: [],
  data() {
    return {
      title: '差标职级映射',
      category: 1, // 当前登录用户的用户类型
      tenantList:[],
      searchForm: {
        businessUnit: "",
        company: "",
        companyDescr: "",
        tenantCode: "",
        standard: "",
        supvLvlId: "",
        crcSupvLvlDesc: ""
      }
    }
  }, 

  computed: {
    ...mapGetters(['isPlatformAdmin']),
    tableConfig() {
      return {
        border:true,
        loadDataFn: this.queryListByPage,
        columnsFn: () => {
          let columns =  [
            {
              title: 'BU编码',
              key: 'businessUnit',
              resizable:true,
              sortable: 'custom',
              render: (h, params) => {
                let title =  params.row['businessUnit'] 
                return h(
                  'div',
                  {
                    attrs: {
                      class: 'ivu-table-cell ivu-table-cell-ellipsis',
                      title: title
                    }
                  },
                  title
                )
              }
            },
            {
              title: '公司编码',
              key: 'company',
              resizable:true,
              sortable: 'custom',
              render: (h, params) => {
                return h(
                  'div',
                  {
                    attrs: {
                      class: 'ivu-table-cell ivu-table-cell-ellipsis',
                      title: params.row['company']
                    }
                  },
                  params.row['company']
                )
              }
            },
            {
              title: '公司名称',
              key: 'companyDescr',
              minWidth: 220,
              resizable:true,
              sortable: 'custom',
              render: (h, params) => {
                return h(
                  'div',
                  {
                    attrs: {
                      class: 'ivu-table-cell ivu-table-cell-ellipsis',
                      title: params.row['companyDescr']
                    }
                  },
                  params.row['companyDescr']
                )
              }
            },
            {
              title: '所属租户',
              key: 'tenantCode',
              align: 'center',
              resizable:true,
              sortable: 'custom',
              minWidth: 180,
              render: (h, params) => {
                let title = this.tenantByName[params.row['tenantCode']] + `(${params.row['tenantCode']})`
                return h(
                  'div',
                  {
                    attrs: {
                      class: 'ivu-table-cell ivu-table-cell-ellipsis',
                      title: title 
                    }
                  },
                  title
                )
              }
            },
             
            {
              title: "差旅编码",
              key: 'standard',
              align: 'center',
              minWidth: 100,
            },
            {
              title: '职级编码',
              key: 'supvLvlId',
              align: 'center',
              minWidth: 100,
            },
            {
              title: '职级名称',
              key: 'crcSupvLvlDesc',
              align: 'center',
              minWidth: 120,
            },
            
            {
              title: '更新时间',
              key: 'updateDate',
              align: 'center',
              resizable:true,
              width:160,
              render: (h, params) => {
                let time = params.row['updateDate'] ? params.row['updateDate'].slice(0,10) : ''
                return h(
                  'div',time
                )
              }
            },
            {
              title: '创建时间',
              key: 'createDate',
              align: 'center',
              resizable:true,
              width:220,
              render: (h, params) => {
                let time = params.row['createDate'] ? params.row['createDate'].slice(0,10) : ''
                return h(
                  'div',time
                )
              }
            },
            {
              title: this.$t('common.operating'),
              align: 'left',
              fixed: 'right',
              resizable:true,
              width: 150,
              render: (h, { row }) => {
              let  data = [
                  {
                    text: '编辑',
                    handle:  debounce(()=>this.onOpenEditPage(row),300)
                  },
                  {
                    text: '删除',
                    handle: debounce(()=>this.onDel(row),300)
                  }
                ]
                return h('RowTools', {
                  props: {
                    data: data
                  }
                })
              }
            }
          ];
          if(!this.isPlatformAdmin){
            columns = columns.filter(item=>{
              if(item.key == 'tenantCode'){
                return false;
              }
              return true;
            })
          } 
          return columns;
        },
        autoFirst: false,
        rowClassNameFn: this.rowClassName // 自定义行样式
      }
    },

    userRolePermission() {
      if ($store.state['ripples-components'].resList) {
        return $util.checkPermission('ROLE_TYPE_USER')
      }
    },

    appRolePermission() {
      if ($store.state['ripples-components'].resList) {
        return $util.checkPermission('ROLE_TYPE_APP')
      }
    },

    tenantByName(){
      let tenantCodes = {};
      this.tenantList.map(item=>{
        tenantCodes[item.tenantCode] = item.tenantName;
      });
      return tenantCodes;
    }
  },

  mounted() {
    if(this.isPlatformAdmin){
      // 平台管理员可以搜索租户信息
      this.$set(this.searchForm,'tenantCode','')
      /**
       * 加载所有租户
       */
        tenantAPI.queryTenantList().then(data => {
        this.tenantList = data;
      })
    }
    this.init()
  },


  methods: {
    // 自定义行样式
    rowClassName(row) {
      //关联的菜单中是否存在有效的hasEnabledMenu:1-存在,0-不存在。enabled:1-有效，0-无效。roleType：1-用户角色，2-应用角色
      if (row.hasEnabledMenu == 0 && row.enabled == 1 && row.roleType == 1) {
        return 'tableDisableStyle'
      }
    },

    async init() {
      let { userInfo } = $store.state[CoreModuleName]
      console.log(userInfo,"userInfouserInfo")
      if (!userInfo) return
      this.category = userInfo.category
      // 根据当前租户查询数据
      // this.searchForm.tenantCode = userInfo.tenantCode
      const [ appData] = await Promise.all([
        // valueSetAPI.getValueSetByCode('ROLE_TYPE'),
        searchAppListByTenantCode({
          pageNum: 1,
          pageSize: 200,
          condition: {
            tenantCode: userInfo.tenantCode
          }
        })
      ])
      // 查询列表
      this.search()
    },

    
    search(page = 1) {
      let searchParams = Object.assign({}, this.searchForm) 
      this.$refs['searchTable'].load(searchParams, page) 
    },

    reset() {
      this.$refs['searchForm'].resetFields() 
      this.search(1)
    }, 
    
    // 删除
    onDel(row){
      new $confirm("您确定要删除该行差标数据吗？", this).then(() => { 
        deleteTSJLM({id:row.id})
          .then(res => {
            this.$message.success({
              content: '删除成功',
              duration: 3
            })
            this.search()
          })
          .catch(data => {
            this.$message.error({
              content: data.message,
              duration: 3
            })
          })
      })
    },

    // 编辑
    onOpenEditPage(row){
      new this.$pageModal(
        () => import('./standardRankDetail.vue'),
        {
          props: {
            id: row.id, 
            detail: row,
          }, 
        },
        data => {
          data && this.search()
        }
      )
    },

    // 新建
    onOpenAddPage:debounce(function(){ 
      new this.$pageModal(
        () => import('./standardRankDetail.vue'),
        {
          props: {
            id:'', 
            detail:{}
          },  
        },
        data => {
          data && this.search()
        }
      )
    },300),
  
    //获取表格数据
    queryListByPage({ responseProcess, param }) {
      return queryTSJLM(param).then(data => {
        if(data.success){ 
          responseProcess(data.data)
        }else{
          this.$message.error({
              content: data.message || "未查询到差标信息",
              duration: 3
          });
          responseProcess({records:[]})
        }
      })
    }
  }
}
</script>

<style></style>
